module service.user_service;

import std.typecons : Nullable;
import d2sqlite3;
import model.user;
import utils.const_val;

/** 
 * 通过用户名获取用户信息
 * Params:
 *   userName = 用户名
 * Returns: Nullable!User
 */
Nullable!User getUserByUsername (string userName)
{
    Database db = Database(CONN_STR);
    Statement statement = db.prepare(
        "SELECT id,username,password,nickname,avatar FROM user WHERE username=:username LIMIT 1;");
    statement.bind(":username", userName);
    ResultRange results = statement.execute();
    scope (exit)
    {
        statement.reset();
    }

    Nullable!User user;
    if (results.empty)
    {
        return user;
    }
    auto row = results.front;
    int id = row["id"].as!int;
    string username = row["username"].as!string;
    string password = row["password"].as!string;
    string nickname = row["nickname"].as!string;
    string avatar = row["avatar"].as!string;
    user = User(
id : id,
username:
        username,
password:
        password,
nickname:
        nickname,
avatar:
        avatar);

    return user;
}
